package com.kajespero.webapp.editor.commons.impl;

import java.beans.PropertyEditorSupport;
import java.lang.reflect.ParameterizedType;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.kajespero.service.commons.ReadService;
import com.kajespero.vo.IdentifierVO;
import com.kajespero.webapp.controller.commons.AbstractController;
import com.kajespero.webapp.editor.commons.IPropertyEditorSupport;

public abstract class AbstractPropertyEditorSupport<S extends ReadService<?, ?, ?, Long>, T extends IdentifierVO<?>> extends PropertyEditorSupport implements IPropertyEditorSupport<S, T> {

	private static final Log LOG = LogFactory.getLog(AbstractController.class);

	private S service;
	
	private Class<T> clazzBean;
	
	public AbstractPropertyEditorSupport(){
		initService();
	}
	

	@SuppressWarnings("unchecked")
	private void initService() {
		ParameterizedType parameterizedType = (ParameterizedType) getClass()
				.getGenericSuperclass();
		LOG.debug("class test == " + getClass());
		Class<S> clazz = (Class<S>) parameterizedType.getActualTypeArguments()[0];
		clazzBean = (Class<T>) parameterizedType.getActualTypeArguments()[1];
		
		try {
			service = (S) clazz.newInstance();
		} catch (InstantiationException e) {
			LOG.error("InstantiationException " + e.getMessage(), e);
		} catch (IllegalAccessException e) {
			LOG.error("IllegalAccessException " + e.getMessage(), e);
		}
	}

	@Override
	public S getService() {
		return this.service;
	}

	@Override
	public Class<T> getBeanClass() {
		return this.clazzBean;
	}

	@SuppressWarnings({ "unchecked" })
	@Override
	public void setAsText(String text) throws IllegalArgumentException{
		if(StringUtils.isNotBlank(text)){
			if(NumberUtils.isNumber(text)){
				Long identifier = Long.parseLong(text);
				T value = (T) getService().find(identifier);
				setValue(value);
			}
		}
	}
}
